import qs from 'qs'
import axios from 'axios'
import Vue from 'vue'
import moment from 'moment'
import store from '../store'
import router from '../router'
import baseURL from './url'

const ajax = axios.create({
  baseURL: baseURL,
  timeout: 30000
})
const vm = new Vue({})
const localAjax = axios.create({})
ajax.interceptors.request.use(config => {
  // vm.$Spin.show()
  // 参数转换为表单模式
  if (config.data) {
    config.data = qs.stringify(config.data)
  }
  // 设置请求头
  config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded', // 模拟form表单方式提交请求
    token: store.getters['session/token'] === undefined ? '' : store.getters['session/token'] // 设置token
  }
  return config
}, error => {
  return Promise.reject(error)
})

ajax.interceptors.response.use((response) => {
  console.log('response', response.data)
  // vm.$Spin.hide()
  // 拦截响应，做统一处理
  if (response.data.code) {
    if (response.data.code === 200) {
      // vm.$Message.success('操作成功')
    } else {
      switch (response.data.code) {
        case 201:
        case 401:
          store.state.isLogin = false
          router.push({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
      }
      vm.$Message.error(response.data.msg)
    }
  }
  return response
}, (error) => {
  console.log('error', error)
  setTimeout(() => {
    vm.$Message.destroy()
  }, 1000)
  return Promise.reject(error)
})

localAjax.interceptors.response.use((respon) => {
  return respon
}, (error) => {
  if (!error.response) {
    vm.$Modal.error('未知错误！')
  }
  setTimeout(() => {
    vm.$Message.destroy()
  }, 1000)
  return Promise.reject(error)
})
export default ajax
export { localAjax }
